package news_api

import (
	"encoding/json"
	"fmt"
	"github.com/fatih/structs"
	"github.com/gin-gonic/gin"
	"giv-vue-blog/models/res"
	"giv-vue-blog/service/redis_ser"
	"giv-vue-blog/utils/request_news"
	"io"
	"time"
)

type Params struct {
	ID   string `json:"id"`
	Size int    `json:"size"`
}
type Header struct {
	Signaturekey string `form:"signaturekey" structs:"signaturekey"`
	Version      string `form:"version" structs:"version"`
	UserAgent    string `form:"User-Agent" structs:"User-Agent"`
}

type NewsResponse struct {
	Code int                  `json:"code"`
	Data []redis_ser.NewsData `json:"data"`
	Msg  string               `json:"msg"`
}

const newsApi = "https://api.codelife.cc/api/top/list"
const timeout = 5 * time.Second

// NewListView 获取新闻列表
// @Summary 获取新闻列表
// @Description 根据参数获取新闻列表
// @Tags 新闻管理
// @Accept json
// @Produce json
// @Param params body Params true "请求参数"
// @Param signaturekey header string true "签名密钥"
// @Param version header string true "版本号"
// @Param User-Agent header string true "User Agent"
// @Success 200 {object} res.Response "操作成功"
// @Router /api/news_list [post]
func (NewsApi) NewListView(c *gin.Context) {
	var cr Params
	var header Header
	err := c.ShouldBindJSON(&cr)
	err = c.ShouldBindHeader(&header)
	if err != nil {
		res.FailedWithCode(res.ArgumentError, c)
		return
	}
	if cr.Size == 0 {
		cr.Size = 1
	}
	key := fmt.Sprintf("%s-%d", cr.ID, cr.Size)
	newData, _ := redis_ser.GetNews(key)
	if len(newData) != 0 {
		res.OkWithData(newData, c)
		return
	}
	httpRsp, err := request_news.Post(newsApi, cr, structs.Map(header), timeout)
	if err != nil {
		res.FailedWithMsg(err.Error(), c)
		return
	}
	var response NewsResponse
	byteData, err := io.ReadAll(httpRsp.Body)
	err = json.Unmarshal(byteData, &response)
	if err != nil {
		res.FailedWithMsg(err.Error(), c)
		return
	}
	//判断code是不是200
	if response.Code != 200 {
		res.FailedWithMsg(response.Msg, c)
		return
	}
	res.OkWithData(response, c)
	redis_ser.SetNews(key, response.Data)
}
